<?php
/**
  * wechat php test
  * update time: 20141008
  */

//define your token
define("TOKEN", "WEIXIN_TEST");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
$wechatObj->responseMsg();
exit;

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
         	//exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>"; 
                if($postObj->MsgType == 'voice'){

                    $Recognition = $postObj->Recognition;      //语音识别结果是object.注意转化。开启语音识别，如果消息类型为语音，就把识别结果给关键字
                    $keyword = (string)$Recognition;
                  }            
				if(!empty( $keyword ))
                {
              		$msgType = "text";
					$contentStr = "您输入的消息是：".$keyword."【type】".$postObj->MsgType."\n\n";

 //--------------------------处理天气示例---------------------------------------------------------------------
                if(strrpos($keyword,'天气') !== false)                            //如果关键字中含有天气字样，进入处理逻辑
                {   
                        require_once('weatherApi.php');
                       
                        $str_repl = trim(str_replace('天气', '', $this->keyword));          //去除关键字中的天气字样，去除空格。
                        $weather  = new Weather($str_repl);
                        $res_array = $weather->GetWeather();                                 //百度api返回正常经纬度的情况下，调用彩云天气api.
                        if(!$res_array['dataseries']||empty($res_array['dataseries'])){
                            $contentStr .= "天气接口异常\n";

                        }
                        if(is_null($weather->weidu) || is_null($weather->jindu)){
                            $contentStr .= "对不起，您输入的地点可能有误！"."\n";

                        }
                        else
                        {
                            $forcat_10_min = Weather::calc_rain_level($res_array['dataseries']);
                            $contentStr = "您查询的地点是：$str_repl"."\n";
                            $contentStr .= "\n";
                            $contentStr .= "经度：".$res_array['location'][1]."\n";
                            $contentStr .= "纬度：".$res_array['location'][0]."\n";
                            if($res_array['descript_now']!='')
                                $contentStr .= "当前天气：".$res_array['descript_now']."\n";
                            $contentStr .= "当前气温：".$res_array['temp']."度\n";
                            $contentStr .= "一小时天气预报：".$res_array['summary']."\n";
                            $contentStr .= "\n";
                            $contentStr .= " 0-10分钟：".$forcat_10_min[0]."\n";
                            $contentStr .= "10-20分钟：".$forcat_10_min[1]."\n";
                            $contentStr .= "20-30分钟：".$forcat_10_min[2]."\n";
                            $contentStr .= "30-40分钟：".$forcat_10_min[3]."\n";
                            $contentStr .= "40-50分钟：".$forcat_10_min[4]."\n";
                            $contentStr .= "50-60分钟：".$forcat_10_min[5]."\n";
                            $contentStr .= "\n";

                            $contentStr .= "<a href='http://caiyunapp.com/#".$res_array['location'][1].",".$res_array['location'][0]."'"."> 去彩云天气查看更多</a>"."\n";

                        }
                }

                //--------------------------天气预报部分结束-------------------------------------------------------------------------

                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                }else{
                	echo "Input something...";
                }

        }else {
        	echo "";
        	exit;
        }
    }
	 public function responseNews()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
                
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <ArticleCount>1</ArticleCount>
                            <Articles>
                            <item>
                            <Title><![CDATA[%s]]></Title>
                            <Description><![CDATA[%s]]></Description>
                            <PicUrl><![CDATA[%s]]></PicUrl>
                            <Url><![CDATA[%s]]></Url>
                            </item>
                            </Articles>
                            </xml>";             
                if(!empty( $keyword ))
                {
                    $msgType = "news";
                    $title = "欢迎关注本公众号"."\n";
                    $Description = "Welcome to wechat world!";
                    $PicUrl ="http://s7.rr.itc.cn/s/wapChange/20163_1_12/a16l5n6638476763352.jpg";
                    $Url    = "http://m.focus.cn";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $title,$Description,$PicUrl,$Url);
                    echo $resultStr;
                }else{
                    echo "Input something...";
                }

        }else {
            echo "";
            exit;
        }
    }	
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>